package com.dtguai.web.web.oss.controller.oss;


import com.alibaba.fastjson.JSON;
import com.dtguai.web.common.error.ErrorCode;
import com.github.pagehelper.PageInfo;
import com.dtguai.web.base.action.BaseAction;
import com.dtguai.web.common.validator.ValidatorUtils;
import com.dtguai.web.common.validator.group.AliyunGroup;
import com.dtguai.web.protocol.response.ApiResponse;
import com.dtguai.web.util.constant.ConfigConstant;
import com.dtguai.web.web.oss.cloud.CloudStorageConfig;
import com.dtguai.web.web.oss.cloud.OssFactory;
import com.dtguai.web.web.oss.model.SysDefOss;
import com.dtguai.web.web.oss.form.oss.OssForm;
import com.dtguai.web.web.oss.form.oss.UploadForm;
import com.dtguai.web.web.oss.service.SysDefOssService;
import com.dtguai.web.web.sys.service.SysDefConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @author guoLiang
 * @date 2018-12-11 02:43:02
 */
@Slf4j
@RestController
@RequestMapping("/web/oss/controller/oss")
@Api(value = "web-文件上传接口", tags = {"web-文件上传接口"})
public class SysDefOssApi extends BaseAction {

    @Autowired
    private SysDefOssService ossService;

    @Autowired
    private SysDefConfigService configService;

    private static final String KEY = ConfigConstant.CLOUD_STORAGE_CONFIG_KEY;

    private static final int FDFS_TYPE = 3;

    private static final int ALIYUN = 2;

    /**
     * 列表
     */
    @ApiOperation(value = "分页查询-返回PageInfo", notes = "分页查询-返回PageInfo")
    @GetMapping(value = "/list", produces = "application/json;charset=UTF-8")
    @RequiresPermissions("sys:oss:all")
    public ResponseEntity<ApiResponse<PageInfo<SysDefOss>>> list(OssForm ossForm) {
        List<SysDefOss> sysDefOssList = ossService.selectByPage(ossForm, true, SysDefOss.class);
        return ResponseEntity.ok(new ApiResponse<PageInfo<SysDefOss>>(new PageInfo<SysDefOss>(sysDefOssList)));
    }

    /**
     * 云存储配置信息
     */
    @ApiOperation(value = "云存储配置信息", notes = "云存储配置信息")
    @GetMapping(value = "/config", produces = "application/json;charset=UTF-8")
    @RequiresPermissions("sys:oss:all")
    public ResponseEntity<ApiResponse<CloudStorageConfig>> config() {
        CloudStorageConfig config = configService.getConfigObject(KEY, CloudStorageConfig.class);
        return ResponseEntity.ok(new ApiResponse<CloudStorageConfig>(config));
    }


    /**
     * 保存云存储配置信息
     */
    @ApiOperation(value = "保存云存储配置信息", notes = "保存云存储配置信息")
    @PostMapping("/saveConfig")
    @RequiresPermissions("sys:oss:all")
    public ResponseEntity<ApiResponse> saveConfig(@RequestBody CloudStorageConfig config) {

        Integer type = Optional.ofNullable(config)
                .map(CloudStorageConfig::getType)
                .orElse(null);
        if (type != null && type == FDFS_TYPE) {
            log.warn("选择了fdfs"+new Date());
        } else if (type != null && type == ALIYUN) {
            ValidatorUtils.validateEntity(config, AliyunGroup.class);
        } else {
            return ResponseEntity.ok(new ApiResponse(ErrorCode.BAD_REQUEST,"暂未开放,敬请期待"));
        }
        configService.updateValueByKey(KEY, JSON.toJSONString(config));

        return ResponseEntity.ok(new ApiResponse());
    }


    /**
     * 上传文件
     */
    @ApiOperation(value = "上传文件", notes = "上传文件")
    @PostMapping("/upload")
    @RequiresPermissions("sys:oss:all")
    public ResponseEntity<ApiResponse<String>> upload(UploadForm up){
        ValidatorUtils.validateEntity(up);
        //上传文件
        String suffix = up.getFile().getOriginalFilename().substring(up.getFile().getOriginalFilename().lastIndexOf("."));
        String url = null;
        try {
            url = OssFactory.build().uploadSuffix(up.getFile().getBytes(), suffix);
        } catch (IOException e) {
            log.error("上传文件出错",e);
        }
        //保存文件信息
        SysDefOss ossEntity = new SysDefOss();
        ossEntity.setUrl(url);
        ossEntity.setCreateTime(new Date());
        ossService.insertSelective(ossEntity);

        return ResponseEntity.ok(new ApiResponse<String>(url));
    }


    /**
     * 删除
     */
    @ApiOperation(value = "保存云存储配置信息", notes = "保存云存储配置信息")
    @DeleteMapping("/delete")
    @RequiresPermissions("sys:oss:all")
    public ResponseEntity<ApiResponse> delete(@RequestBody List<Integer> ids) {
        ossService.deleteByIds(ids, SysDefOss.class);
        return ResponseEntity.ok(new ApiResponse());
    }

}